<template>
  <div class="main-back">
    <MainTitle :main-title="mainTitle" />
    <dv-loading v-show="runFlag" class="loading">Loading...</dv-loading>
    <div :class="['gif-bg', {hide : !processFlag}]" />
    <div class="main-item">
      <div class="item item-current">
        <div class="tag-item">
          <el-button class="view-button" type="primary" @click="openView">原理简介</el-button>
          <tag-card v-for="(item,index) in itemdata" :key="index" ref="tag-card" class="tag-card" :item="item" @setFlow="setFlow" />
        </div>
        <main-charts>
          <div v-show="hasNoData" class="no-data">暂无数据</div>
          <div v-for="(item, index) in eqmList" :key="index" class="main-body">
            <eqm-card class="eqm-card" :sum="flow_sum_origin" :is-result="false" :eqm="item" :index="index+1" />
          </div>
        </main-charts>
      </div>
      <div class="item item-result">
        <div v-show="!processFlag" class="result-control">
          <div v-if="!aiResult.value && aiResult.value!==0" class="item-result-title">人工智能大数据模型</div>
          <div v-else class="result">
            <div v-if="!processFlag && parseFloat(optimizationRate) && parseFloat(optimizationRate)>0">
              <div class="result-title">预计能耗节约：<span>{{ savingEnergy }}</span></div>
              <div class="result-detail">历史耗电量：{{ historyElec }}kWh</div>
              <div class="result-detail">优化耗电量：{{ optimizeElec }}kWh</div>
            </div>
            <div v-else-if="!processFlag && parseFloat(optimizationRate)<0 || parseFloat(optimizationRate)===0" class="result-best">太棒了！当前开机模式已经是最佳。</div>
            <diV v-else class="result-best">数据出错</diV>
          </div>
          <el-button type="primary" class="item-button" :disabled="runFlag" @click="getSuggestionResult">运行</el-button>
        </div>
      </div>
      <div class="item item-suggest">
        <SystemSwitch class="system-buttons" :current-system="system" @setSystem="setSystem" />
        <el-button class="view-button1" type="primary" :disabled="dataGet" @click="openSetting">压力设置与荷载分布</el-button>
        <main-charts>
          <div v-show="hasNoData" class="no-data">暂无数据</div>
          <div v-for="(item, index) in suggestionResult" :key="index" class="main-body">
            <eqm-card class="eqm-card" :sum="flow_sum_origin" :is-result="true" :eqm="item" :index="index+1" />
          </div>
        </main-charts>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { data } from './data/itemcard.json'
import 'element-ui/lib/theme-chalk/index.css'

export default {
  components: {
    MainTitle: () => import('@/components/MainTitle.vue'),
    EqmCard: () => import('./module/EqmCard.vue'),
    TagCard: () => import('./module/tagCard.vue'),
    MainCharts: () => import('./module/mainCharts.vue'),
    SystemSwitch: () => import('@/components/SystemSwitch.vue')
  },
  props: {
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      systemMap: { 'hcda': 'HCDA', 'lcda': 'LCDA', 'low_chiller': '低温冰机',
        'medium_chiller': '中温冰机' },
      itemdata: data,
      eqmList: [],
      eqmResultList: [],
      originFlow: null,
      settedFlow: null,
      aiResult: {
        payload: []
      },
      system: 'hcda',
      runFlag: false,
      hasNoData: false,
      processFlag: false,
      // mainTitle: '智慧节能-CDA开机建议',
      savingEnergy: null,
      historyElec: null,
      optimizeElec: null,
      PerSettedElec: null,
      optimizationRate: null,
      flow_sum_origin: null,
      flow_sum_result: null
    }
  },
  computed: {
    mainTitle() {
      return '智慧节能-' + this.title
    },
    ...mapState({
      service: state => state.service,
      webModel: state => state.authentication.webModel,
      treeTemplate: state => state.component.treeTemplate
    }),
    originElec() {
      return this.itemdata.find(e => e.type === 'elec').value ? this.itemdata.find(e => e.type === 'elec').value : null
    },
    PerOriginElec() {
      return (this.originElec / this.originFlow).toFixed(2)
    },
    suggestInit() {
      const tmp = { 'status': 2, 'load': '' }
      return this.eqmResultList.map(e => ({ ...e, ...tmp }))
    },
    suggestionResult() {
      return this.suggestInit.map(e => ({ ...e, ...(this.aiResult.payload || []).find(i => i.machine === e.id) }))
    }
  },
  created() {
    this.init('hcda')
  },

  methods: {
    openView() {
      this.$router.push({ name: 'IntroductionOfSuggestion' })
    },
    openSetting() {
      this.$router.push({ name: 'pressureSetting' })
    },
    setSystem(system) {
      this.system = system
      this.init(system)
    },
    async init(system) {
      this.runFlag = true
      this.loading = 0
      this.aiResult = {
        payload: []
      }
      try {
        const result = await this.service.getBootSuggestion({ 'id': system })
        // const result = {
        //   'data': [
        //     { 'id': '1#High_Pressure_Air_Compressor', 'ic': '8221', 'i': '222', 'info': { 'specCurrent': '1040', 'specOutputFlow': '2333', 'c': '8155229.4921875', 'i': '0.300000012', 's': '0', 'ip': '7.33400011', 'bov': '0', 'igv': '0', 'icon': 'Air_Compressor', 'load': '0.172413799999999978' }, 'name': '1#高压离心压缩机' },
        //     { 'id': '2#High_Pressure_Air_Compressor', 'ic': '8321', 'i': '222', 'info': { 'specCurrent': '1140', 'specOutputFlow': '2133', 'c': '7232269.53125', 'i': '121.900002', 's': '-1', 'ip': '7.23300028', 'bov': '35.0999985', 'igv': '92.6699982', 'icon': 'Air_Compressor', 'load': '70.0574724137931071' }, 'name': '2#高压离心压缩机' },
        //     { 'id': '3#High_Pressure_Air_Compressor', 'ic': '8421', 'i': '222', 'info': { 'specCurrent': '1240', 'specOutputFlow': '2233', 'c': '8445638.671875', 'i': '0.300000012', 's': '0', 'ip': '7.35200024', 'bov': '0', 'igv': '0', 'icon': 'Air_Compressor', 'load': '0.172413799999999978' }, 'name': '3#高压离心压缩机' },
        //     { 'id': '999#High_Pressure_Screw_Air_Compressor', 'ic': '8521', 'i': '222', 'info': { 'specCurrent': '1340', 'specOutputFlow': '3113', 'c': '1735616', 'i': '453.760009765625', 's': '-1', 'ip': '7.49300051', 'icon': 'Screw_Air_Compressor', 'load': '32.8811601279438435' }, 'name': '1#高压螺杆压缩机' }
        //   ], 'flag': true }
        if (!result.flag || !result.data) {
          this.runFlag = false
          this.hasNoData = true
          return
        }
        this.eqmResultList = result.data
        this.eqmList = result.data
        let sum = 0
        this.eqmList.forEach((item, index) => {
          sum = sum + item.data.i / item.info.specCurrent * item.info.specOutputFlow
        })
        this.flow_sum_origin = sum
        this.hasNoData = !(this.eqmList && this.eqmList.length)
        const machineHourlyResult = await this.service.getMachineHourlyValue({ 'id': system })
        if (!machineHourlyResult.flag || !machineHourlyResult.data) {
          this.runFlag = false
          return
        }
        const hourlyResult = machineHourlyResult.data
        let elec = '25753'
        let flow = '29845'
        hourlyResult.forEach(e => {
          if (e.tag_id === 'c') {
            elec = e.value ? e.value.toFixed(2) : '-'
          }
          if (e.tag_id === 'ic') {
            flow = e.value ? e.value.toFixed(2) : '-'
            this.originFlow = e.value ? e.value.toFixed(2) : '-'
          }
        })
        this.itemdata = [
          {
            'type': 'elec',
            'name': '耗电量',
            'value': elec
          },
          {
            'type': 'prod',
            'name': '产气量',
            'value': flow
          }
        ]
        this.settedFlow = this.itemdata.find(e => e.type === 'prod') ? this.itemdata.find(e => e.type === 'prod').value : null
        this.runFlag = false
      } catch (e) {
        this.$notify({
          title: '请求失败',
          type: 'error',
          duration: 2500
        })
        this.runFlag = false
        this.hasNoData = true
      }
    },
    async getSuggestionResult() {
      const flow = this.itemdata.find(e => e.type === 'prod')
      this.settedFlow = this.settedFlow && this.settedFlow !== '-' && flow ? this.settedFlow : flow.value
      if (this.system === 'hcda' && (this.settedFlow >= 53000 || this.settedFlow < 3200)) {
        this.$notify({
          title: '产气量不在能够实现的范围内，设置范围为：3200~53000',
          type: 'error',
          duration: 2500
        })
        return
      }
      if (this.system === 'lcda' && (this.settedFlow >= 98000 || this.settedFlow < 3200)) {
        this.$notify({
          title: '产气量不在能够实现的范围内，设置范围为：3200~98000',
          type: 'error',
          duration: 2500
        })
        return
      }
      try {
        this.processFlag = true
        const requestParam = JSON.stringify({
          system: this.system,
          tag: {
            oq: parseInt(this.settedFlow),
            elec: parseInt((this.settedFlow / this.originFlow * this.originElec))
          }
        })
        const aiResult = await this.service.getSuggestionResult(requestParam)
        aiResult.value = Math.floor(aiResult.value)
        this.aiResult = aiResult
        this.aiResult.value = aiResult.value
        this.PerSettedElec = (aiResult.value / this.settedFlow).toFixed(2)
        this.optimizationRate = ((this.PerOriginElec - this.PerSettedElec) / this.PerOriginElec * 100).toFixed(2)
        this.savingEnergy = this.optimizationRate !== 'NaN' ? this.optimizationRate + '%' : '-'
        this.historyElec = (this.settedFlow / this.originFlow * this.originElec).toFixed(0)
        this.optimizeElec = aiResult.value ? aiResult.value : '-'
        let sum = 0
        for (let x = 0; x++; x < this.suggestionResult.length) {
          sum = sum + this.suggestionResult[x].i / this.suggestionResult[x].info.specCurrent * this.suggestionResult[x].info.specOutputFlow
        }
        this.flow_sum_result = sum
        this.processFlag = false
        console.log('optimizationRate', this.optimizationRate)
      } catch (e) {
        this.processFlag = false
        this.$notify({
          title: '请求失败',
          type: 'error',
          duration: 2500
        })
      }
    },
    setFlow(e) {
      this.settedFlow = e.target.value
    },

    sleep(time) {
      return new Promise((resolve) => setTimeout(resolve, time))
    }
  }
}
</script>
<style lang="scss" scoped>
.main-back{
  display: flex;
  flex-flow: column nowrap;
  align-items: stretch;
  background-image: url('~@assets/report/bg.png');
  background-size: 100% 100%;
  height: 100vh;
  overflow: hidden;
  position: relative;
}
.view-button{
  width: 8rem;
  height: 8rem;
  line-height: 2rem;
  font-size: 1rem;
  color:#FFF;
  background: url('~@assets/report/jiejingshi.png') no-repeat center top;
  background-size: 50%;
  border: none;
  border-radius: 0;
  padding: 3.3rem 10px 0;
  }
.item-current{
  width: 25%;
}
.item-result{
  position: relative;
}
.item-result .result-control{
    position: absolute;
    top: 55%;
    left: 50%;
    width: 14rem;
    height: 10rem;
    margin-left: -7rem;
    margin-top: -5rem;
    display: flex;
    flex-flow: column nowrap;
    justify-content: space-around;
}
.item-result-title{
  font-size: 1.4rem;
  padding-top: 0.5%;
  color: white;
  align-self: center;
}
.gif-bg{
  background: url('~@assets/report/bg2.gif') no-repeat top;
  background-size: 100% 100%;
  position: absolute;
  width: 90%;
  height: 77%;
  left: 5%;
  top: 10%;
}
.main-item{
  flex-grow: 1;
  display:flex;
  flex-flow: row nowrap;
  justify-content: space-around;
  background: url('~@assets/report/bg2.png') no-repeat top;
  background-size: 100% 100%;
  position: absolute;
  width: 90%;
  height: 77%;
  left: 5%;
  top: 10%;
}
.item{
  flex-grow: 3;
  display: flex;
  flex-flow: column nowrap;
  height: 75vh;
  width: 33%;
}

.item-result{
  flex-grow: 1;
 display: flex;
 flex-flow: column nowrap;
 align-items: stretch;
 justify-content: flex-start;
}
.tag-item{
  margin-bottom: 33px;
  display: flex;
  flex-flow: row nowrap;
  align-items: flex-start;
  color: #00f4ff;
  margin: 0 2%;
}
.tag-suggess{
  align-items: flex-end;
}

.item-button{
  width: 8.3rem;
  align-self: center;
  color: white;
  font-size: 1.4rem;
  background-color:transparent;
  border-color: #00f4ff;
  border-radius: 0%;
  margin-top: 5px;
}
.item-left{
  margin-left: auto;
}
.main-body{
  flex: 1;
  display: flex;
  flex-flow: row nowrap;
}
.result-loading{
  border: 0 !important;
}
.result{
  height: 6rem;
  color: #fff;
  display:flex;
  flex-flow: column;
  justify-content: space-around;
  align-items:center;
}
.result-title{
  font-size: 1.2rem;
  font-weight: 600;
}
.result-title span{
  font-size: 1.3rem;
}
.result-best{
  font-size: 1.5rem;
  font-weight: 600;
  text-align: center;
}
.item-title{
  color: #fff;
  margin: 0;
}
.item-title.title1{
  text-align:right;
}
.item-title.title2{
  text-align:left;
  width: 60%;
}
.gif-bg.show{
  display: block;
}
.gif-bg.hide{
  display: none;
}
.system-buttons{
  justify-content: flex-end;
  margin-bottom: 1.3rem;;
}
.item-suggest .main-charts{
  margin-top: 25px;
}
.no-data{
  position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    background: rgb(10,12,31);
    font-size: 20px;
    text-align: center;
    padding-top: 10rem;
}
.loading{
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba($color: #333, $alpha: 0.7);
  z-index: 9;
}
.view-button1{
    float: right;
    font-size: 1rem;
    color:white;
    align-self: flex-end;
    background-color: #05417f !important;
    border: 0;
    border-radius: 0;
    padding: 12px 10px;
  }
</style>
